package com.heima.behavior.service.impl;

import com.alibaba.fastjson.JSON;
import com.heima.behavior.service.BehaviorService;
import com.heima.common.constants.CacheConstants;
import com.heima.common.constants.HotArticleConstants;
import com.heima.common.exception.CustomException;
import com.heima.model.behavior.dtos.LikesBehaviorDto;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.mess.UpdateArticleMess;
import com.heima.model.user.pojos.ApUser;
import com.heima.utils.thread.AppThreadLocalUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;

/**
 * @author brianxia
 * @version 1.0
 * @date 2022-10-30 9:10
 */
@Service
@Slf4j
public class BehaviorServiceImpl implements BehaviorService {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private KafkaTemplate<String,String> kafkaTemplate;

    @Override
    public void likes(LikesBehaviorDto dto) {

        ApUser user = AppThreadLocalUtil.getUser();
        if(user == null){
            throw new CustomException(AppHttpCodeEnum.NEED_LOGIN);
        }

        //1.确定数据结构 set  key
        String key = CacheConstants.LIKES + dto.getArticleId();
        String userIdStr = user.getId().toString();

        Boolean member = stringRedisTemplate.opsForSet().isMember(key, userIdStr);

        if(dto.getOperation() == 0){
            if(member != null && member){
                //保证一定程度上的幂等
                return;
            }
            //2.判断是点赞 将数据保存
            stringRedisTemplate.opsForSet().add(key,userIdStr);
            //发消息
        }else{
            if(member == null || !member){
                //保证一定程度上的幂等
                return;
            }
            //3.取消点赞，将数据删除
            stringRedisTemplate.opsForSet().remove(key,userIdStr);
        }

        UpdateArticleMess updateArticleMess = new UpdateArticleMess();
        updateArticleMess.setArticleId(dto.getArticleId());
        updateArticleMess.setType(UpdateArticleMess.UpdateArticleType.LIKES);
        updateArticleMess.setAdd(dto.getOperation() == 0? 1 : -1 );

        kafkaTemplate.send(HotArticleConstants.HOT_ARTICLE_INCR_HANDLE_TOPIC,
                JSON.toJSONString(updateArticleMess));

    }
}
